<?php

namespace app\admin\controller\home;

use app\common\controller\Backend;
use think\Db;

/**
 * 资讯项目
 *
 * @icon fa fa-circle-o
 */
class Project extends Backend
{

    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];
    protected $relationSearch = true;

    /**
     * @var \app\admin\model\User
     */
    protected $model = null;
    protected $models = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Project;
        $this->models = new \app\admin\model\Reports;

        $categorys = Db::table('fa_categorys')
            ->where('type',1)
            ->select();
        $this->view->assign('categorys', $categorys);
    }

    /**
     * 查看
     */
    public function index()
    {

        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                //->with(['categorys'=>['id,name']])
                ->with([
                    'categorys' => function ($query) {
                        $query->withField('id,name');
                    }
                ])
                ->where($where)
                //->where('admin_id', 'in', [0])
                ->order('id', $order)
                ->paginate($limit);

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }

        return $this->view->fetch();
    }


    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            $arr = $params['report'];
            $arrs = array_merge($params['status']);
            $params['report'] = implode(',', $params['report']);
            $params['create_time'] = time();
            unset($params['status']);
            if ($params) {
                $params = $this->preExcludeFields($params);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }

                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    //$result = $this->model->allowField(true)->save($params);
                    $result = $this->model->allowField(true)->insertGetId($params);

                    foreach ($arr as $k=>$v){
                        $insert[$k]['project_id'] = $result;
                        $insert[$k]['report_name'] = $v;
                        $insert[$k]['status'] = $arrs[$k];
                        $insert[$k]['create_time'] = time();
                    }


                    if ((count($arr) == 1) && (empty($arr[0]))){
                        $inserts = 1;
                    }else{
                        $inserts = Db::table('fa_reports')
                            ->insertAll($insert);
                    }


                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if (($result !== false) && ($inserts !== false)) {
                    Db::commit();
                    $this->success();
                } else {
                    Db::rollback();
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }


    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }

        $rows = Db::table('fa_reports')
            ->where('project_id',$ids)
            ->order('id','asc')
            ->select();
        $ids = [];
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");

            if (isset($params['report'])){
                foreach ($params['report'] as $k=>$v){
                    $ids[] = $k;
                    $update[$k]['id'] = $k;
                    $update[$k]['project_id'] = $row->id;
                    $update[$k]['report_name'] = $v;
                    $update[$k]['status'] = $params['status'][$k];
                    $update[$k]['update_time'] = time();
                }
                $update = array_merge($update);
                unset($params['status']);
            }else{
                $params['report'] = '';
                $is_report = '';
            }


            if (isset($params['reports'])){
                if (!empty($params['report'])){
                    $report = implode(',', $params['report']).','.implode(',', $params['reports']);
                }else{
                    $report = implode(',', $params['reports']);
                }

                $arr = $params['reports'];
                $arrs = array_merge($params['statuss']);
                unset($params['reports']);
                unset($params['statuss']);
            }else{
                $arr = [];
                $report = empty($params['report']) ? '':implode(',', $params['report']);
            }

            $params['report'] = $report;
            $params['update_time'] = time();

            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);


                    foreach ($rows as $k=>$v){
                        if (!in_array($v['id'],$ids)){
                            Db::table('fa_reports')
                                ->where('id',$v['id'])
                                ->delete();
                        }
                    }

                    if (!empty($is_report)){
                        $updates = $this->models->saveAll($update);
                    }


                    if (!empty($arr)){
                        foreach ($arr as $k=>$v){
                            $insert[$k]['project_id'] = $row->id;
                            $insert[$k]['report_name'] = $v;
                            $insert[$k]['status'] = $arrs[$k];
                            $insert[$k]['create_time'] = time();
                        }

                        $inserts = Db::table('fa_reports')
                            ->insertAll($insert);
                    }

                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }

        $this->view->assign("rows", $rows);
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }


}
